import $ from 'jquery';
import { Base64 } from 'js-base64';
import { nameConfig } from '@theme/vm';
import { getQueryParamByName, isIOS } from '@/common/js/common';
import '../style/download-web-ky.scss';
import request from '../js/request';
const SITE_NAME = process.env.SITE_NAME || '';
let app_android_download = '';
let app_ios_download = '';
const ios_download = nameConfig.ios_download; // ios线上包地址
const android_download = nameConfig.android_download; // 安卓线上包地址
const imgPath = SITE_NAME + '_appdown';
const i_code: any = getQueryParamByName('i_code');
const r_code = getQueryParamByName('r_code');

// 判断是否是手机浏览器
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
function redirectToDownloadIfMobile() {
  // 获取当前路径
  const currentPath = window.location.pathname;

  // 检查路径是否包含 download_com.html
  const pathContainsDownloadCom = currentPath.includes('download_com.html');

  // 如果是手机浏览器并且路径包含 download_com.html，跳转到 download.html
  if (isMobile && pathContainsDownloadCom) {
    window.location.href =
      window.location.origin + '/download.html' + window.location.search;
  }
}

/**
 * web入口文件
 * @export
 * @param {*} type 区分全站体育
 */
export default function (type: 'sport' | 'site') {
  document.title =
    Base64.decode(nameConfig.welComeText) + Base64.decode(nameConfig.sportName);
  redirectToDownloadIfMobile();
  initGetInfo();
  initEvent();
  initVerticalBtns();
}

// 请求前置信息
function initGetInfo() {
  request({
    url: '/api/findmed/v2/member/preInfo',
    method: 'post',
    params: {},
    callback: (res: any) => {
      if (res.status) {
        const resData = res?.data;

        if (resData?.customer_service) {
          document
            .querySelector<HTMLElement>('.customer_service')
            .addEventListener('click', function (e) {
              e.preventDefault();
              window.location.href = resData?.customer_service;
            });
        }

        app_ios_download =
          resData?.site_domain?.app_ios_download || ios_download;
        app_android_download =
          resData?.site_domain?.app_android_download || android_download;
        // 这里循环判断返回的下载地址是否包含i_code或r_code，如果有就替换原来的下载地址
        const navigation_domain = resData?.site_domain?.pc_navigation_domain;
        const domainArr = navigation_domain.split(',');
        const urlParams = i_code ? '?i_code=' + i_code : '';

        const urlData = [];
        domainArr.forEach((item, index) => {
          if (index < 3) urlData.push(item + urlParams);
        });

        let html = '';
        for (let i = 0; i < 3; i++) {
          const url = urlData[i] ? urlData[i] : urlData[0];
          html += `<a class="domain-item" href="${url}"  target="_blank">
                            <div class="time_text">${12}ms</div>
                            <div class="text" style="overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;margin-left:25px;width:200px">${url}</div>
                        </a>`;
        }
        const speedList = document.querySelector<HTMLElement>('#domainList');
        if (speedList) {
          speedList.innerHTML = html;
        }
      }
    },
    fail: (err: any) => {
      console.log(err);
    },
  });
}

function initEvent() {
  setInterval(function () {
    setSign();
  }, 1500);
}

function setSign() {
  var signalDelayElement = document.querySelectorAll('.time_text');
  for (var i = 0; i < signalDelayElement.length; i++) {
    var tmpElement = signalDelayElement[i];
    var count = Math.random() * 5;

    if (count < 1) {
      var max = 10;
      var min = 6;
      var random = (Math.random() * (max - min) + min).toFixed(2) + 'ms';

      setInnerText(tmpElement, random);
    } else if (count > 3) {
      var random = Math.random().toFixed(2) + 'ms';
      setInnerText(tmpElement, random);
    } else {
      var max = 5;
      var min = 2;
      var random = (Math.random() * (max - min) + min).toFixed(2) + 'ms';
      setInnerText(tmpElement, random);
    }
  }
}

function setInnerText(element, text) {
  if (typeof element.textContent == 'string') {
    element.textContent = text;
  } else {
    element.innerText = text;
  }
}

function initVerticalBtns() {
  const installVb = document.querySelector<HTMLElement>('#installVb');
  if (installVb) {
    installVb.addEventListener('click', function () {
      if (isIOS()) {
        window.location.href = app_ios_download;
      } else {
        window.location.href = app_android_download;
      }
    });
  }
}
